#!/bin/bash

# AISH 跨平台编译脚本
# 支持 Windows, Linux, macOS 多架构编译

set -e  # 遇到错误时退出

# 项目信息
APP_NAME="aish"
VERSION=$(git describe --tags --always --dirty 2>/dev/null || echo "dev")
BUILD_TIME=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
GO_VERSION=$(go version | awk '{print $3}')

# 输出目录
OUTPUT_DIR="dist"
SOURCE_FILE="cmd/main.go"

# ANSI 颜色代码
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 显示帮助信息
show_help() {
    echo -e "${CYAN}AISH 跨平台编译脚本${NC}"
    echo ""
    echo "用法: $0 [选项] [平台]"
    echo ""
    echo "选项:"
    echo "  -h, --help     显示帮助信息"
    echo "  -v, --version  显示版本信息"
    echo "  -c, --clean    清理构建目录"
    echo "  --dev          开发模式编译（不优化）"
    echo ""
    echo "平台:"
    echo "  all            编译所有平台 (默认)"
    echo "  windows        编译 Windows (amd64, 386)"
    echo "  linux          编译 Linux (amd64, arm64, 386)"
    echo "  macos          编译 macOS (amd64, arm64)"
    echo "  current        仅编译当前平台"
    echo ""
    echo "示例:"
    echo "  $0                    # 编译所有平台"
    echo "  $0 windows            # 仅编译 Windows"
    echo "  $0 --clean            # 清理构建目录"
    echo "  $0 --dev linux        # 开发模式编译 Linux"
}

# 清理构建目录
clean_build() {
    log_info "清理构建目录: $OUTPUT_DIR"
    rm -rf "$OUTPUT_DIR"
    log_success "构建目录已清理"
}

# 检查依赖
check_dependencies() {
    if ! command -v go &> /dev/null; then
        log_error "Go 编译器未安装或不在 PATH 中"
        exit 1
    fi
    
    log_info "Go 版本: $GO_VERSION"
    log_info "项目版本: $VERSION"
    log_info "构建时间: $BUILD_TIME"
}

# 编译单个目标
build_target() {
    local goos=$1
    local goarch=$2
    local output_name=$3
    
    # Windows 需要 .exe 扩展名
    if [[ "$goos" == "windows" ]]; then
        output_name="${output_name}.exe"
    fi
    
    local output_path="$OUTPUT_DIR/${goos}-${goarch}/$output_name"
    
    log_info "编译 ${goos}/${goarch} -> $output_path"
    
    # 创建输出目录
    mkdir -p "$(dirname "$output_path")"
    
    # 编译标志
    local ldflags=""
    if [[ "$DEV_MODE" != "true" ]]; then
        ldflags="-s -w"  # 去除调试信息和符号表
    fi
    
    # 设置环境变量并编译
    env GOOS=$goos GOARCH=$goarch go build \
        -trimpath \
        -ldflags="$ldflags" \
        -o "$output_path" \
        "$SOURCE_FILE"
    
    if [[ $? -eq 0 ]]; then
        local size=$(ls -lh "$output_path" | awk '{print $5}')
        log_success "编译成功: ${goos}/${goarch} ($size)"
    else
        log_error "编译失败: ${goos}/${goarch}"
        return 1
    fi
}

# 编译 Windows
build_windows() {
    log_info "开始编译 Windows 平台"
    build_target "windows" "amd64" "$APP_NAME"
    build_target "windows" "386" "$APP_NAME"
}

# 编译 Linux
build_linux() {
    log_info "开始编译 Linux 平台"
    build_target "linux" "amd64" "$APP_NAME"
    build_target "linux" "arm64" "$APP_NAME"
    build_target "linux" "386" "$APP_NAME"
}

# 编译 macOS
build_macos() {
    log_info "开始编译 macOS 平台"
    build_target "darwin" "amd64" "$APP_NAME"
    build_target "darwin" "arm64" "$APP_NAME"
}

# 编译当前平台
build_current() {
    local current_os=$(go env GOOS)
    local current_arch=$(go env GOARCH)
    log_info "编译当前平台: ${current_os}/${current_arch}"
    build_target "$current_os" "$current_arch" "$APP_NAME"
}

# 编译所有平台
build_all() {
    log_info "开始编译所有平台"
    build_windows
    build_linux
    build_macos
}

# 显示构建摘要
show_summary() {
    echo ""
    log_info "构建摘要:"
    echo "----------------------------------------"
    
    if [[ -d "$OUTPUT_DIR" ]]; then
        find "$OUTPUT_DIR" -type f -executable -o -name "*.exe" | while read -r file; do
            local size=$(ls -lh "$file" | awk '{print $5}')
            local relative_path=${file#$OUTPUT_DIR/}
            echo "  $relative_path ($size)"
        done
    else
        log_warning "构建目录不存在"
    fi
    
    echo "----------------------------------------"
    log_success "构建完成!"
}

# 主函数
main() {
    local target="all"
    
    # 解析命令行参数
    while [[ $# -gt 0 ]]; do
        case $1 in
            -h|--help)
                show_help
                exit 0
                ;;
            -v|--version)
                echo "$APP_NAME version $VERSION"
                exit 0
                ;;
            -c|--clean)
                clean_build
                exit 0
                ;;
            --dev)
                DEV_MODE="true"
                shift
                ;;
            all|windows|linux|macos|current)
                target=$1
                shift
                ;;
            *)
                log_error "未知选项: $1"
                show_help
                exit 1
                ;;
        esac
    done
    
    # 检查依赖
    check_dependencies
    
    # 创建输出目录
    mkdir -p "$OUTPUT_DIR"
    
    # 根据目标执行编译
    case $target in
        all)
            build_all
            ;;
        windows)
            build_windows
            ;;
        linux)
            build_linux
            ;;
        macos)
            build_macos
            ;;
        current)
            build_current
            ;;
        *)
            log_error "未知目标: $target"
            exit 1
            ;;
    esac
    
    # 显示摘要
    show_summary
}

# 执行主函数
main "$@"
